<script setup lang="ts">
// import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import {
  ElButton,
  ElImage,
  ElMessageBox,
  ElMessage,
  ElBreadcrumb,
  ElTabPane,
  ElTabs,
  ElTag,
  ElContainer,
  ElScrollbar,
  ElAside,
  ElMain,
  ElHeader
} from 'element-plus'
import { ArrowRight } from '@element-plus/icons-vue'
import { Table } from '@/components/Table'
import {
  sysFileEditApi,
  sysFileDelApi,
  sysFileBatchShiftApi,
  sysFileBatchDelApi,
  sysFileListApi,
  sysFileSeeBreadcrumbApi,
  sysFileFolderTreeApi,
  sysFileAddApi,
  sysFileBatchCopyApi
} from '@/api/file'
import { useTable } from '@/hooks/web/useTableTest'
import { ref, unref, reactive, h, onBeforeMount } from 'vue'
import EditFolder from './components/EditFolder.vue'
import EditImg from './components/EditImg.vue'
// import EditFile from './components/EditFile.vue'
// import Edit from './components/Edit.vue'
import File from './components/File.vue'
import FileCopy from './components/FileCopy.vue'
import SeeFolder from './components/SeeFolder.vue'
import SeeFile from './components/SeeFile.vue'
import { useRoute } from 'vue-router'
import { useIcon } from '@/hooks/web/useIcon'
import { useCache } from '@/hooks/web/useCache'
const route = useRoute()
const { wsCache } = useCache()
const userInfo: any = wsCache.get('userInfo')
const dict: any = wsCache.get('dict')

const belong_type: any = dict.belong_type
const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconDel = useIcon({ icon: 'ep:delete' })

const parent_id: any = route.query.parent_id ? ref(route.query.parent_id) : ref('0')
const tabValue = ref('1')
const folder_name_arr: any = ref([])

const datafolderTree: any = ref([])
const getfolderTree = async () => {
  const res = await sysFileFolderTreeApi({
    belong_type: tabValue.value
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    datafolderTree.value = res.data
    if (tabValue.value == '1') {
      datafolderTree.value.unshift({ id: '0', parent_id: '0', name: '我的附件' })
    } else {
      datafolderTree.value.unshift({ id: '0', parent_id: '0', name: '组织附件' })
    }
  }
}
const getfolderListA = async (val) => {
  val.belong_type = tabValue.value
  val.parent_id = parent_id.value
  return sysFileListApi(val)
}

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: getfolderListA,
  response: {
    data: 'data',
    count: 'count'
  }
})

const getListBreadcrumb = async () => {
  const res: any = await sysFileSeeBreadcrumbApi({
    id: parent_id.value
  })
    .catch(() => {})
    .finally(() => {})
  if (res) {
    folder_name_arr.value = res.data
    if (tabValue.value == '1') {
      folder_name_arr.value.unshift({ id: '0', parent_id: '0', name: '我的附件' })
    } else {
      folder_name_arr.value.unshift({ id: '0', parent_id: '0', name: '组织附件' })
    }
    folder_name_arr.value[folder_name_arr.value.length - 1].last = '/'
  }
}

// const datafolderList = ref<any>([])
const { getList } = methods

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'images',
    label: '文件',
    width: 300,
    fixed: 'left',
    search: { show: false },
    form: { show: false },
    detail: { show: true }
  },
  {
    field: 'belong_type',
    label: '所属类型',
    detail: {
      show: true
    },
    table: {
      show: false
    }
  },
  {
    field: 'file_type',
    label: '文件类型',
    width: 90,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return h(
        ElTag,
        {
          type:
            cellValue == '1'
              ? 'success'
              : cellValue == '2'
              ? 'danger'
              : cellValue == 'other'
              ? 'info'
              : 'warning'
        },
        () =>
          cellValue == '1'
            ? '图片'
            : cellValue == '2'
            ? '文件'
            : cellValue == 'other'
            ? '其他'
            : '文件夹'
      )
    },
    form: {
      show: false
    },
    search: {
      component: 'Select',
      componentProps: {
        options: [
          {
            label: '图片',
            value: '0'
          },
          {
            label: '文件',
            value: '1'
          }
        ]
      }
    },
    detail: {
      show: true
    }
  },
  {
    field: 'file_size',
    label: '文件大小',
    table: { show: true },
    search: { show: false },
    form: { show: false },
    detail: { show: true }
  },
  {
    field: 'create_user_name',
    label: '创建人',
    table: { show: true },
    search: { show: false },
    form: { show: true },
    detail: { show: false }
  },
  {
    field: 'create_time',
    label: '创建时间',
    width: 180,
    table: { show: true },
    search: { show: false },
    form: {
      show: true,
      componentProps: {
        disabled: true
      }
    },
    detail: { show: false }
  },
  {
    field: 'action',
    width: 300,
    fixed: 'right',
    label: '操作',
    form: { show: false },
    detail: { show: false }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)
const dialogVisible = ref(false)

const dialogTitle = ref('')

const delLoading = ref(false)
// const shiftLoading = ref(false)

const delData = async () => {
  delLoading.value = true
  let res = await sysFileBatchDelApi({
    parent_id: parent_id.value,
    belong_type: belong_type.value,
    checkedAll: false,
    selected: selected
  })
    .catch(() => {})
    .finally(() => {
      delLoading.value = false
    })
  if (res) {
    getList()
  }
}
const selected: any = ref([])
const actionType = ref('')
let addFolder = ref()
let imageSee = ref('')
// const folder_selected = ref([])
const action = async (type: string, row: any = {}) => {
  actionType.value = type
  const { getSelections } = methods
  const selectData = await getSelections()
  selected.value = []
  selectData.forEach((v: any) => {
    selected.value.push(v.id)
  })
  switch (type) {
    case 'add_folder':
      dialogTitle.value = '新增文件夹'
      // console.log(row, 'rwo ')
      addFolder.value = row
      if (!row.belong_type) {
        addFolder.value.belong_type = tabValue.value
      }
      dialogVisible.value = true
      break
    case 'edit_folder':
      dialogTitle.value = '编辑文件夹'
      addFolder.value = row
      dialogVisible.value = true
      break
    case 'see_folder':
      dialogTitle.value = '查看文件夹'
      addFolder.value = row
      dialogVisible.value = true
      break
    case 'add_img':
      dialogTitle.value = '新增文件'
      tableObject.currentRow = row
      tableObject.currentRow.org_name = userInfo.default_org_name
      tableObject.currentRow.org_id = userInfo.default_org_id
      tableObject.currentRow.parent_id = parent_id.value
      if (!row.belong_type) {
        tableObject.currentRow.belong_type = tabValue.value
      }
      dialogVisible.value = true
      break
    case 'edit_img':
      dialogTitle.value = '编辑文件'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'see_file':
      dialogTitle.value = '查看文件信息'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del_file':
      ElMessageBox.confirm('确定要删除这个文件吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiFileDel(row)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    case 'batch_del':
      if (selected.value.length > 0) {
        ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), {
          confirmButtonText: t('common.delOk'),
          cancelButtonText: t('common.delCancel'),
          type: 'warning'
        })
          .then(() => {
            delData()
          })
          .catch(() => {
            console.log('这里是取消confirm弹框')
          })
      } else {
        ElMessage({
          type: 'warning',
          message: '不能没有选择'
        })
      }
      break
    case 'batch_shift':
      dialogTitle.value = '批量转移'
      dialogVisible.value = true
      break
    case 'batch_copy':
      dialogTitle.value = '批量复制'
      dialogVisible.value = true
      break
    case 'image':
      dialogTitle.value = '附件'
      imageSee.value = row.file_url
      dialogVisible.value = true
      break
    default:
      console.log('未知类型')
  }
}

const apiFileDel = async (row) => {
  let delRes = await sysFileDelApi({ id: row.id })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (delRes) {
    if (row.is_file == '0') {
      getfolderTree()
    }
    getList()
  }
}

const editImgRef = ref<ComponentRef<typeof EditImg>>()
const editFolderRef = ref<ComponentRef<typeof EditFolder>>()
const batchFileRef = ref<ComponentRef<typeof File>>()
const batchCopyRef = ref<ComponentRef<typeof FileCopy>>()
const loading = ref(false)

const save = async () => {
  const editImg = unref(editImgRef)
  const editFolder = unref(editFolderRef)
  const batchFile = unref(batchFileRef)
  const batchCopy = unref(batchCopyRef)
  switch (actionType.value) {
    case 'add_folder':
      await editFolder?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await editFolder?.getFormData()) as any
          const val: any = {
            is_file: '0',
            parent_id: parent_id.value,
            name: data.name,
            belong_type: data.belong_type
          }
          let res = await sysFileAddApi(val)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            getList()
          }
        }
      })

      break
    case 'add_img':
      await editImg?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const dataForm = (await editImg?.getFormData()) as any
          const dataFile: any = editImg?.fileData
          if (dataFile.file_type == 'image') {
            dataFile.image_width = dataFile.img_data.width
            dataFile.image_height = dataFile.img_data.height
          } else {
          }
          dataFile.is_file = '1'
          dataFile.name = dataForm.name
          dataFile.parent_id = dataForm.parent_id
          dataFile.belong_type = dataForm.belong_type
          dataFile.org_id = userInfo.default_org_id
          dataFile.file_type = dataFile.file_type == 'image' ? '1' : '2'
          let res = await sysFileAddApi(dataFile)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            tableObject.currentPage = 1
            getList()
          }
        }
      })

      break
    case 'edit_img':
      await editImg?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await editImg?.getFormData()) as any
          // console.log(data.image_height, 'data')
          if (data.img_data) {
            // console.log(data.image_height, 'data')
            data.image_width = data.img_data.width
            data.image_height = data.img_data.height
            data.file_type = data.file_type == 'image' ? '1' : '2'
            data.is_file = '1'
          }
          let res = await sysFileEditApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            getList()
          }
        }
      })
      break
    case 'edit_folder':
      await editFolder?.elFormRef?.validate(async (isValid) => {
        if (isValid) {
          loading.value = true
          const data = (await editFolder?.getFormData()) as any
          let res = await sysFileEditApi(data)
            .catch(() => {})
            .finally(() => {
              loading.value = false
            })
          if (res) {
            dialogVisible.value = false
            getList()
          }
        }
      })
      break
    case 'batch_shift':
      const target_parent_id = (await batchFile?.getFormData())?.id
      if (target_parent_id == parent_id.value) {
        ElMessageBox.alert('不能转移到当前文件夹下', t('common.delWarning'), {
          cancelButtonText: '确定',
          type: 'warning'
        }).then(async () => {
          delLoading.value = false
        })
      } else {
        loading.value = true
        let res = await sysFileBatchShiftApi({
          past_parent_id: parent_id.value,
          belong_type: tabValue.value,
          target_parent_id: target_parent_id,
          checkedAll: false,
          selected: selected.value
        })
          .catch(() => {})
          .finally(() => {
            loading.value = false
          })
        if (res) {
          dialogVisible.value = false
          tableObject.currentPage = 1
          getList()
        }
      }

      break
    case 'batch_copy':
      const target_parent_copy_id = (await batchCopy?.getFormData())?.id
      const target_belong_type = (await batchCopy?.getFormData())?.belong_type
      // if (target_parent_copy_id == parent_id.value) {
      //   ElMessageBox.alert('不能转移到当前文件夹下', t('common.delWarning'), {
      //     cancelButtonText: '确定',
      //     type: 'warning'
      //   }).then(async () => {
      //     delLoading.value = false
      //   })
      // } else {
      console.log(userInfo.default_org_id, 'userInfo.default_org_id,')
      const params = {
        my_org_id: userInfo.default_org_id,
        past_parent_id: Number(parent_id.value),
        past_belong_type: tabValue.value,
        target_belong_type: target_belong_type,
        target_parent_id: target_parent_copy_id,
        checkedAll: false,
        selected: selected.value
      }
      console.log(params, 'params,')
      loading.value = true
      console.log(sysFileBatchCopyApi, 'sysFileBatchCopyApi', sysFileBatchCopyApi)
      // let res = await sysFileBatchCopyApi(JSON.stringify(params))
      let res = await sysFileBatchCopyApi(params)
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
      if (res) {
        dialogVisible.value = false
        tableObject.currentPage = 1
        getList()
      }
      // }
      break
    default:
      console.log('未知类型')
  }
}

const init = async () => {
  await getList()
  await getListBreadcrumb()
}
init()
onBeforeMount(() => {
  getfolderTree()
})

const dblclick = async (a) => {
  if (a.is_file == 0) {
    parent_id.value = a.id
    selectedNode.value.id = a.id
    selectedNode.value.color = '#409EFF'
    selectedNode.value.fontWeight = 900
    // parent_name.value = a.folder_name
    getListBreadcrumb()
    getList()
  } else {
    const url = a.file_url // 打开的地址
    window.open(url)
  }
}
const selectedNode: any = ref({
  id: String,
  color: String,
  fontWeight: Number
})
selectedNode.value.color = '#409EFF'
selectedNode.value.fontWeight = 900
selectedNode.value.id = '0'
const Breadcrumb = (val, i) => {
  console.log(val, i, '面包屑')
  selectedNode.value.id = val.id
  selectedNode.value.color = '#409EFF'
  selectedNode.value.fontWeight = 900
  folder_name_arr.value = folder_name_arr.value.slice(0, i + 1)
  parent_id.value = val.id
  // if (folder_name_arr.value.length > 1) {
  getList()
  // }
}
const handleChange = (val) => {
  console.log(val, '切换')
  tabValue.value = val
  folder_name_arr.value = []
  if (val == 1) {
    folder_name_arr.value = [{ id: '0', parent_id: '0', name: '我的附件' }]
  } else {
    folder_name_arr.value = [{ id: '0', parent_id: '0', name: '组织附件' }]
  }
  selectedNode.value.id = 0
  parent_id.value = '0'
  getList()
  getfolderTree()
}

const handleNodeClick = (node) => {
  selectedNode.value.color = '#409EFF'
  selectedNode.value.fontWeight = 900
  selectedNode.value.id = node.id
  parent_id.value = node.id
  // folder_name_arr
  getListBreadcrumb()
  getList()
}
let selectData: any = ref([])

const changeSelect = async () => {
  selectData.value = tableObject.tableList.filter((item) => item.checkbox === true)
}
</script>

<template>
  <ElContainer class="layout-container-demo">
    <ElAside width="230px">
      <ElTabs v-model="tabValue" class="demo-tabs" @tab-change="handleChange(tabValue)">
        <ElTabPane
          :label="item.label"
          :name="item.value"
          v-for="(item, index) in belong_type"
          :key="index"
        />
      </ElTabs>
      <ElScrollbar>
        <ElTree
          ref="treeRef"
          :data="datafolderTree"
          :props="{ children: 'children', label: 'name' }"
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <span
              :style="{
                color: data.id == selectedNode.id ? selectedNode.color : 'inherit',
                fontWeight: data.id == selectedNode.id ? selectedNode.fontWeight : 'inherit'
              }"
            >
              {{ node.label }}
            </span>
          </template>
        </ElTree>
      </ElScrollbar>
    </ElAside>
    <ElContainer>
      <ElHeader height="">
        <!-- <Search
          :schema="allSchemas.searchSchema"
          @search="setSearchParams"
          @reset="setSearchParams"
        /> -->
        <div class="mb-10px">
          <ElButton type="primary" @click="action('add_folder', {})">新增文件夹</ElButton>
          <ElButton type="primary" @click="action('add_img', {})">新增文件</ElButton>
          <ElButton type="" @click="action('batch_shift', {})"> 批量转移 </ElButton>
          <ElButton type="" @click="action('batch_copy', {})"> 批量复制 </ElButton>
          <ElButton :loading="delLoading" type="danger" @click="action('batch_del', {})">
            批量删除
          </ElButton>
        </div>

        <ElBreadcrumb :separator-icon="ArrowRight" class="breadcrumb-separator">
          <ElBreadcrumbItem
            v-for="(item, i) in folder_name_arr"
            :key="i"
            @click="Breadcrumb(item, i)"
          >
            {{ item.name }}
          </ElBreadcrumbItem>
        </ElBreadcrumb>
      </ElHeader>
      <ElMain>
        <Table
          v-model:pageSize="tableObject.pageSize"
          v-model:currentPage="tableObject.currentPage"
          :columns="allSchemas.tableColumns"
          :data="tableObject.tableList"
          :loading="tableObject.loading"
          :pagination="{
            total: tableObject.count
          }"
          row-key="id"
          :selection="true"
          @register="register"
          @row-dblclick="dblclick"
        >
          <template #checkbox="{ row }">
            <ElCheckbox @change="changeSelect()" v-model="row.checkbox" :disabled="!row.file_url" />
          </template>
          <template #images="{ row }">
            <div v-if="row.is_file == 1">
              <ElImage
                v-if="row.file_type == 1"
                style="width: 40px; height: 40px; border-radius: 10px"
                :src="row.file_url"
              />
              <ElImage
                v-if="row.suffix_name == 'doc' || row.suffix_name == 'docx'"
                style="width: 40px; height: 40px; border-radius: 10px"
                src="https://docs.gtimg.com/docs-design-resources/document-management/tencent-docs/png@3x/application-vnd.tdocs-apps.doc@3x.png"
              />
              <ElImage
                v-if="row.suffix_name == 'xls' || row.suffix_name == 'xlsx'"
                style="width: 40px; height: 40px; border-radius: 10px"
                src="https://docs.gtimg.com/docs-design-resources/document-management/tencent-docs/png@3x/application-vnd.tdocs-apps.sheet@3x.png"
              />
              <ElImage
                v-if="row.suffix_name == 'ppt'"
                style="width: 40px; height: 40px; border-radius: 10px"
                src="https://docs.gtimg.com/docs-design-resources/document-management/tencent-docs/png-200px/application-vnd.tdocs-apps.slide.png"
              />
              <ElImage
                v-if="row.suffix_name == 'file'"
                style="width: 40px; height: 40px; border-radius: 10px"
                src="https://docs.gtimg.com/docs-design-resources/document-management/tencent-docs/png-200px/application-vnd.tdocs-apps.folder.png"
              />
              <ElImage
                v-if="row.suffix_name == 'txt'"
                style="width: 40px; height: 40px; border-radius: 10px"
                src="https://img1.baidu.com/it/u=4162092432,2125414077&fm=253&fmt=auto&app=138&f=JPEG?w=450&h=300"
              />
              <span class="span" style="padding-left: 5px">{{
                row.name + '.' + row.suffix_name
              }}</span>
            </div>
            <div v-if="row.is_file == 0">
              <Icon
                color="#E6A23C"
                icon="ion:folder-sharp"
                :size="40"
                style="border-radius: 10px"
              />
              <span class="span" style="padding-left: 5px">{{ row.name }}</span>
            </div>
          </template>
          <template #file_size="{ row }">
            <span v-if="row.is_file == 1">{{ row.file_size + `KB` }}</span>
            <span v-else></span>
          </template>
          <template #action="{ row }">
            <ElButton
              v-if="row.is_file == '0'"
              type="primary"
              :icon="iconEdit"
              @click="action('edit_folder', row)"
            >
              编辑
            </ElButton>
            <ElButton v-else type="primary" :icon="iconEdit" @click="action('edit_img', row)">
              编辑
            </ElButton>
            <ElButton
              v-if="row.is_file == '0'"
              type="success"
              :icon="iconSee"
              @click="action('see_folder', row)"
            >
              详情
            </ElButton>
            <ElButton v-else type="success" :icon="iconSee" @click="action('see_file', row)">
              详情
            </ElButton>
            <ElButton type="danger" :icon="iconDel" @click="action('del_file', row)">
              删除
            </ElButton>
          </template>
        </Table>
      </ElMain>
    </ElContainer>
  </ElContainer>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <EditFolder
      v-if="actionType == 'add_folder' || actionType == 'edit_folder'"
      ref="editFolderRef"
      :addFolder="addFolder"
    />
    <EditImg
      v-if="actionType == 'edit_img' || actionType == 'add_img'"
      ref="editImgRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />
    <SeeFolder
      v-if="actionType == 'see_folder'"
      :detail-schema="allSchemas.detailSchema"
      :addFolder="addFolder"
    />
    <SeeFile
      v-if="actionType == 'see_file'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />
    <!-- 批量转移 -->
    <File v-if="actionType == 'batch_shift'" ref="batchFileRef" :datafolderTree="datafolderTree" />
    <!-- 批量复制 -->
    <FileCopy
      v-if="actionType == 'batch_copy'"
      ref="batchCopyRef"
      :datafolderTree="datafolderTree"
    />
    <img
      v-if="actionType == 'image' && tableObject.tableList"
      w-full
      :src="imageSee"
      alt="Preview Image"
    />
    <template #footer>
      <ElButton
        v-if="
          actionType !== 'see' &&
          actionType !== 'see_file' &&
          actionType !== 'image' &&
          actionType !== 'see_folder' &&
          actionType !== 'batch_shift'
        "
        type="primary"
        :loading="loading"
        @click="save()"
      >
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton
        v-if="actionType == 'batch_shift'"
        type="primary"
        :loading="loading"
        @click="save()"
      >
        转移到此
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
<style lang="less" scoped>
// .el-table td.el-table__cell div {
//   display: flex;
//   .span {
//     line-height: 40px;
//     margin-left: 10px;
//   }
// }
.el-aside {
  overflow: hidden;
}
.el-header {
  height: auto;
  --el-header-height: 0;
}

.el-tree {
  background: transparent;
}
.el-main {
  padding-top: 0;
}
.el-breadcrumb__item:last-child {
  font-weight: bold;
  color: red;
}
.el-breadcrumb {
  line-height: 2;
}
</style>
